from MediaInfoDLL  import * 
from PyFlac.Carbon import CarbonUtils
from PyFlac.Carbon import CarbonJob
from PyFlac.Carbon import CarbonSocketLayer
from PyFlac.Ardome import ArdXML
from PyFlac import TimeCode
import sys, os, time

#SMB_PATH_IN   = '\\\\10.221.173.151\\Avid\\in\\'
#SMB_PATH_OUT  = '\\\\10.221.173.151\\Avid\\out'
#GUID_43       = '{DB64C4B7-EB3E-4CBC-8B65-2C9BCA1B1A39}'
#GUID_169      = '{5F3972E5-BFA3-49AD-8A5C-BF3FE8C98746}'	
#XML	      = './PG-60822-2-HOGAREXPRESS2010-HE60-EPISODIO60-VDPM.mxf.xml'
#MXF	      = 'PG-60822-2-HOGAREXPRESS2010-HE60-EPISODIO60-VDPM.mxf'
#MEDIA_PATH    = '/data/Avid/in/'



#
# Deberia estar en TimeCode
#

def msToFrames(ms):
        f = 1000.0 / 29.97
        return int(round( ms / f ))


class TransCarbon(object):
	def __init__(self, carbon_host = None, src_path = None, dst_path = None, local_path = None, local_dst_path = None):
		self.carbon_host    = carbon_host
		self.src_path       = src_path
		self.dst_path       = dst_path
		self.local_path	    = local_path
		self.local_dst_path = local_dst_path
		self.mxf	    = None
		self.recipeCarbon   = None
		self.errors	    = ''
		self.JobList	    = []

	def Start(self, mxf, recipeCarbon):
		self.mxf = mxf
		self.recipeCarbon = recipeCarbon

		if self.mxf and self.recipeCarbon:
			# 
			# Observar el Objeto y cargar el JobList
			# 
			if self.recipeCarbon.SegmentType == 'None':
				#
				# No Requiere Cortes
				#

				#
				# Si la receta no tiene basename, crearlo desde el nombre original del File
				#				

        			if self.recipeCarbon.Basename == None:
                			(basename,ext) = self.mxf.split(".")
				else:	
					basename = self.recipeCarbon.Basename

				
				#
				# Prueba la existencia del file que se va a transcodificar
				#	 - Si existe lo borra
				#
				if os.path.isfile(self.local_dst_path + basename + self.recipeCarbon.Ext):
					os.unlink(self.local_dst_path + basename + self.recipeCarbon.Ext)


				#
                                # Carga en la lista los nombres de los files que van a salir luego del procesi de transocde
                                #


				f = basename+self.recipeCarbon.Ext

				self.JobList.append( {'Job': TransCarbonCutNone(self.mxf, basename, self.carbon_host, self.recipeCarbon.Guid, self.src_path, self.dst_path), 'File' : f, 'Finish': False } )

			elif self.recipeCarbon.SegmentType == 'Stich':
				#
				# Requiere Cortes pero unidos
				#	


				if self.recipeCarbon.Basename == None:
                                        (basename,ext) = self.mxf.split(".")
                                else:
                                        basename = self.recipeCarbon.Basename


                                #
                                # Prueba la existencia del file que se va a transcodificar
                                #        - Si existe lo borra
                                #
                                if os.path.isfile(self.local_dst_path + basename + self.recipeCarbon.Ext):
                                        os.unlink(self.local_dst_path + basename + self.recipeCarbon.Ext)

				

				
				#
                                # Carga en la lista los nombres de los files que van a salir luego del procesi de transocde
                                #



				f = basename+self.recipeCarbon.Ext

				frames = self.__MediaFramesDelay()
				cut_info = []			
				for s in self.recipeCarbon.Segments:
					cut_info.append(s.In + ',' + s.Out)

				self.JobList.append( { 'Job': TransCarbonCutStich(self.mxf,frames,cut_info,basename,self.carbon_host,self.recipeCarbon.Guid,self.src_path,self.dst_path), 'File':f, 'Finish': False})


			elif self.recipeCarbon.SegmentType == 'Segment':
				#
				# Requiere Cortes Segmentados
				#
				frames = self.__MediaFramesDelay()
                                for s in self.recipeCarbon.Segments:

					if s.Basename == None:
                                        	(basename,ext) = self.mxf.split(".")
                                	else:
                                        	basename = s.Basename


                                	#
                                	# Prueba la existencia del file que se va a transcodificar
                                	#        - Si existe lo borra
                                	#
                                	if os.path.isfile(self.local_dst_path + basename + self.recipeCarbon.Ext):
                                        	os.unlink(self.local_dst_path + basename + self.recipeCarbon.Ext)

					#
					# Carga en la lista los nombres de los files que van a salir luego del procesi de transocde
					#

					f = basename+self.recipeCarbon.Ext					

					self.JobList.append({'Job':TransCarbonCutSegment(self.mxf,frames,s.In,s.Out,basename,self.carbon_host,self.recipeCarbon.Guid,self.src_path,self.dst_path), 'File': f, 'Finish': False } ) 
			
		
		#
		# Envio todos los Jobs
		# 
		for Job in self.JobList:
			Job['Job'].Start()


	def WaitFinish(self):
		end = False
		ret = [] 
		while not end:
			for job in self.JobList:
				# Por Cada Job
				#
				# - Si todavia no termino					

				if job['Finish'] == False:
					status = job['Job'].GetStatus(True)
					if status == "COMPLETED":
						if os.path.isfile(self.local_dst_path+job['File']):
							job['Finish'] = True
							ret.append(job['File'])
						else:
							end = True
							self.errors = 'Transcode Finish but not destination file in filesystem: ' + self.local_path+job['File']


					elif status != "STARTED" and status != "QUEUED":
						#
						# Error
						#
						end = True
						self.errors = 'Carbon Failed transcoding: ' + self.local_dst_path+job['File']
			b = True

			for job in self.JobList:
				b = b and job['Finish']


		
			if b:
				end = True

			if not end:
				time.sleep(30)
	

		return ret


	def __MediaFramesDelay(self):
		#
		# Si el file esta local puedo capturar el Start Timecode
		#
		if os.path.isfile(self.local_path+self.mxf):
			MI = MediaInfo()
                	MI.Open(self.local_path+self.mxf)
                	delay = MI.Get(Stream.Video, 0, u"Delay")
                	MI.Close()
			return msToFrames(int(delay))
		#
		# Sino, lo invento :P
		#
		else:
			return 0




#xml = ArdXML.ArdXML(XML)


#for s in xml.Metadata.segments:
#	print s.SOM


#CutMediaSegments(MXF, xml.Metadata.segments, '10.221.173.31', GUID_169, SMB_PATH_IN, SMB_PATH_OUT)

 



